package com.qdu.controller;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.qdu.entity.Bussiness;
import com.qdu.service.BussinessService;
import com.qdu.service.SocketService;
import com.qdu.util.DateUtil;

@Controller
@RequestMapping("/buss")
public class BussinessController {

	@Autowired
	BussinessService bs;
	
	@Autowired
	SocketService socket;
	
	@PostMapping("/add")
	@ResponseBody
	public String addBuss(@RequestParam Map<String,Object> buss,@RequestParam("bimg") MultipartFile img) throws IllegalStateException, IOException {
		
		System.out.print(buss.toString());
		String oldName=img.getOriginalFilename();
		//这里调用UUID类的静态方法randomUUID()生成一个UUID值作为文件新名称
		//去掉其中的中划线，并且连接上文件的扩展名
		String newName=UUID.randomUUID().toString().replace("-","")
				       +oldName.substring(oldName.lastIndexOf("."));
		
		System.out.println("文件新名称："+newName); 
		String today=DateUtil.getToday();
		//获取/static/img的真实路径
		String realPath=new String("src/main/resources/static/bimg");//ResourceUtils.getURL("classpath:static/static/uimg").getPath();
		System.out.println("/static/img的真实路径："+realPath);

		
		File folder=new File(realPath+"/"+today);
		if(!folder.exists()) //如果文件夹不存在，则创建文件夹，如果存在，不重复创建
			folder.mkdirs(); //创建文件夹
		
		//调用transferTo()方法将接受的文件转移到指定文件
		//这里需要用一个File对象指定文件所在目录和文件名
		img.transferTo(new File(folder,newName));
		String path = "bimg/"+today+'/'+newName;
		
		Bussiness b = new Bussiness();
		b.setBname(buss.get("bname").toString());
		b.setBpro(buss.get("bpro").toString());
		b.setBaddress(buss.get("baddress").toString());
		b.setBcity(buss.get("bpro").toString());
		b.setNumber(Integer.parseInt(buss.get("number").toString()));
		b.setBimg(path);
		b.setBdetails(buss.get("bdetails").toString());
	//	b.setBimg(path);
		int row = bs.insert(b);
		
		if(row>0)
			{
			WebSocket.SendMessage(socket.getAllData("有新企业注册，请关注"));
			return "注册成功，请等待审核";
			
			}
		else
			return "注册失败，请重试";
	}
}
